package com.gmlive.common.network.domain.request;

import com.gmlive.common.network.domain.entity.DomainBean;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import io.reactivex.Observable;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @Author sven
 * @Date 2020/5/20
 */
public class DomainRepository {

    private OkHttpClient okHttpClient = null;

    private Map<String, Retrofit> retrofitMap = new HashMap<>();

    private static DomainRepository instance = null;

    public static DomainRepository get(OkHttpClient okHttpClient) {
        if (instance == null) {
            synchronized (DomainRepository.class) {
                if (instance == null) {
                    instance = new DomainRepository();
                    instance.init(okHttpClient);
                }
            }
        }

        return instance;
    }

    private void init(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
    }

    public DomainBean getDomain(String domain, String path, Map<String, String> params) throws IOException {
        if (!domain.startsWith("https://") && !domain.startsWith("http://")) {
            if (isIP(domain)) {
                domain = "http://" + domain;
            } else {
                domain = "https://" + domain;
            }
        }
        /*if (!domain.startsWith("http://")) {
            domain = "http://" + domain;
        }*/
        Retrofit retrofit = getRetrofit(domain);
        DomainService service = retrofit.create(DomainService.class);
        return service.getDomain(path, params).execute().body();
    }

    private Retrofit getRetrofit(String baseUrl) {
        Retrofit retrofit = retrofitMap.get(baseUrl);
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .client(okHttpClient)
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();

            retrofitMap.put(baseUrl, retrofit);
        }

        return retrofit;
    }

    private static boolean isIP(CharSequence input) {
        return isMatch("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)", input);
    }

    private static boolean isMatch(final String regex, final CharSequence input) {
        return input != null && input.length() > 0 && Pattern.matches(regex, input);
    }
}
